﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DO.Workflows
{
    public class Timer: WorkflowTrigger
    {
        #region Overrides of WorkflowComponentBase

        private TimerInstruction _Instruction;
        public override InstructionBase Instruction
        {
            get { return _Instruction; }
            set { _Instruction=(TimerInstruction)value; }
        }

        private TimerOutput _Output;
        public override ResultBase Output
        {
            get { return _Output; }
            set { _Output=(TimerOutput)value; }
        }

        #endregion

        #region ctor
        public Timer():base()
        {
            this.ComponentName = "Timer";
            this.Description = "Start workflow recursively using schedule";

            this._Instruction = new TimerInstruction();
            this._Output = new TimerOutput();
        }
        #endregion

        #region Overrides of WorkflowTrigger

        public override TriggerType TriggerType
        {
            get { return TriggerType.Timer; }
        }

        public override bool CanRun()
        {
            if (!this._Instruction.IsActive)
                return false;
            if(this._Instruction.LastRunTime.HasValue)
            {
                if(this._Instruction.LastRunTime.Value.Add(this._Instruction.Span)<DateTime.Now)
                    return true;
                else
                    return false;
            }
            else
                return true;
        }

        public override void UpdateNextRun()
        {
            this._Instruction.LastRunTime = DateTime.Now;
            this._Instruction.NextRunTime =
                this._Instruction.LastRunTime.Value.Add(this._Instruction.Span);
        }

        public override ResultBase[] ProcessTrigger(ref WorkflowTriggerInstructionBase instruction)
        {
            if(instruction==null || instruction.GetType()!=typeof(TimerInstruction))
                throw new Exception("Invalid instruction for timer");
            DateTime now = DateTime.Now;
            TimerInstruction timerInstruction = (TimerInstruction) instruction;
            if (timerInstruction.LastRunTime == null || timerInstruction.LastRunTime.Value.Add(timerInstruction.Span) <= now)
            {
                instruction.LastRunTime = now;
                instruction.NextRunTime = now + instruction.Span;
                TimerOutput output = new TimerOutput
                {
                    ComponentID = this.ComponentID,
                    FinishTime = DateTime.Now,
                    JobID = Guid.NewGuid()
                };
                return new ResultBase[] { output };
            }
            else
                return null;
        }
        #endregion
    }
}
